package com.magic.websocket.handle;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import com.google.common.collect.Maps;

@Component
public class DefaultWebSocketHander extends TextWebSocketHandler {

	private static final Logger logger = LoggerFactory.getLogger(DefaultWebSocketHander.class);

	private static Map<String, WebSocketSession> webSocketSessions = Maps.newConcurrentMap();

	/**
	 * ①创建连接 ②身份认证 ③业务支持
	 * 
	 * @see org.springframework.web.socket.handler.AbstractWebSocketHandler#afterConnectionEstablished(org.springframework.web.socket.WebSocketSession)
	 */
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		logger.debug("[websocket]:" + session.getId() + " request connect");
		logger.debug("[websocket]:" + session.getId() + " request connect success");
		webSocketSessions.put(session.getId(), session);
	}

	public static void sendMessageToGame(String message) {
		if (!webSocketSessions.isEmpty()) {
			TextMessage textMessage = new TextMessage(message);
			for (Entry<String, WebSocketSession> entry : webSocketSessions.entrySet()) {
				try {
					entry.getValue().sendMessage(textMessage);
				} catch (IOException e) {
					logger.error("DefaultWebSocketHander.sendMessageToGame()方法异常{}:{}", e.getMessage(), e);
				}
			}
		}
	}

	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		System.out.println(message.getPayload());
	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
	}

	/**
	 * 
	 * ①关闭连接 ②业务支持
	 * 
	 * @see org.springframework.web.socket.handler.AbstractWebSocketHandler#afterConnectionClosed(org.springframework.web.socket.WebSocketSession,
	 *      org.springframework.web.socket.CloseStatus)
	 */
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		logger.debug("[websocket]:" + session.getId() + " close connect");
		webSocketSessions.remove(session.getId());
		logger.debug("[websocket]:" + session.getId() + " close connect success");
	}

}
